<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单词" prop="word">
        <el-input
          v-model="queryParams.word"
          placeholder="请输入单词"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!--      <el-form-item label="词库ID" prop="bankId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.bankId"-->
      <!--          placeholder="请输入词库ID"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:item:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:item:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:item:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:item:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleAllTransfer"
        >全部转正式库
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleTransferCurrent"
        >批量转正式
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="单词" align="center" prop="word"/>
      <el-table-column label="近义词" align="center" prop="synonyms"/>
      <el-table-column label="美式音标" align="center" prop="usPhonetics"/>
      <el-table-column label="英式音标" align="center" prop="ukPhonetics"/>

      <el-table-column label="美式发音" align="center" prop="usVoice">
        <template slot-scope="scope">
          <el-button type="text" @click="playAudio(scope.row.usVoice)" icon="el-icon-headset"/>
        </template>
      </el-table-column>
      <el-table-column label="英式发音" align="center" prop="ukVoice">
        <template slot-scope="scope">
          <el-button type="text" @click="playAudio(scope.row.ukVoice)" icon="el-icon-headset"/>
        </template>
      </el-table-column>
      <el-table-column label="词性" align="center" prop="wordType"/>
      <!--      <el-table-column label="含义列表" align="center" prop="meanings" />-->
      <el-table-column label="解释" align="center" prop="meaning"/>
      <el-table-column label="中文解释" align="center" prop="chineseMeaning"/>
      <el-table-column label="配图" align="center" prop="picture">
        <template slot-scope="scope">
          <el-image :src="scope.row.picture" :preview-src-list="[scope.row.picture]" class="el-avatar">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="选中的正式例句" align="center" prop="chosenExample"/>
      <el-table-column label="例句集合" align="center" prop="examples">、
        <template slot-scope="scope">
          <el-button type="text" @click="handleExamples(scope.row)" icon="el-icon-plus">查看</el-button>
        </template>
      </el-table-column>
      <!--      <el-table-column label="词库ID" align="center" prop="bankId" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleTransferCurrent(scope.row)"
            v-hasPermi="['system:item:edit']"
          >转正式
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:item:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:item:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改词汇原型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单词" prop="word">
          <el-input v-model="form.word" placeholder="请输入单词"/>
        </el-form-item>
        <el-form-item label="近义词" prop="synonyms">
          <el-input v-model="form.synonyms" placeholder="请输入近义词"/>
        </el-form-item>
        <el-form-item label="美式音标" prop="usPhonetics">
          <el-input v-model="form.usPhonetics" placeholder="请输入美式音标"/>
        </el-form-item>
        <el-form-item label="英式发音" prop="ukPhonetics">
          <el-input v-model="form.ukPhonetics" placeholder="请输入英式发音"/>
        </el-form-item>
        <el-form-item label="美式发音" prop="usVoice">
          <el-input v-model="form.usVoice" placeholder="请输入美式发音"/>
        </el-form-item>
        <el-form-item label="英式发音" prop="ukVoice">
          <el-input v-model="form.ukVoice" placeholder="请输入英式发音"/>
        </el-form-item>
        <el-form-item label="含义列表" prop="meanings">
          <el-input v-model="form.meanings" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="含义" prop="meaning">
          <el-input v-model="form.meaning" placeholder="请输入含义"/>
        </el-form-item>
        <el-form-item label="含义中文意思" prop="chineseMeaning">
          <el-input v-model="form.chineseMeaning" placeholder="请输入含义中文意思"/>
        </el-form-item>
        <el-form-item label="配图" prop="picture">
          <el-input v-model="form.picture" placeholder="请输入配图"/>
        </el-form-item>
        <el-form-item label="选中的例句" prop="chosenExample">
          <el-input v-model="form.chosenExample" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
<!--        <el-form-item label="例句集合" prop="examples">-->
<!--          <el-input v-model="form.examples" type="textarea" placeholder="请输入内容"/>-->
<!--        </el-form-item>-->
        <el-form-item label="词库ID" prop="bankId">
          <el-input v-model="form.bankId" placeholder="请输入词库ID"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="titleExamples" :visible.sync="openExamples" width="1200px" append-to-body>
      <el-table
        :data="myExamples"
        style="width: 100%">
        <el-table-column
          label="例句"
          >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.english }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="翻译"
     >
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.translation }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="toFormer(scope.$index, scope.row)">选为正式</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import {
  addItem,
  delItem,
  getItem,
  listItem,
  turnExampleByWordId,
  turnExamplesByBankId,
  updateItem,
  transferItem
} from "@/api/wordmemory/vocabulary_item";

export default {
  name: "Item",
  data() {
    return {
      curWordId: -1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 词汇原型表格数据
      itemList: [],
      // 弹出层标题
      title: "",
      titleExamples: "",
      // 是否显示弹出层
      open: false,
      openExamples: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        word: null,
        synonyms: null,
        usPhonetics: null,
        ukPhonetics: null,
        usVoice: null,
        ukVoice: null,
        wordType: null,
        uid: null,
        meanings: null,
        meaning: null,
        chineseMeaning: null,
        picture: null,
        chosenExample: null,
        examples: null,
        bankId: null
      },
      // 表单参数
      form: {},
      audio: new Audio(), // 创建一个audio实例
      myExamples: [],
      // 表单校验
      rules: {
        word: [
          {required: true, message: "单词不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.queryParams.bankId = this.$route.params && this.$route.params.id;
    this.getList();
  },
  methods: {

    handleTransferCurrent(row) {
      const ids = row.id || this.ids;
      transferItem(ids).then(response => {
        if (response.code === 200) {
          this.loading = false;
          this.$message({
            message: "转正式成功",
            type: "success"
          });
        }
      });
    },
    handleAllTransfer() {
      const bankId = this.$route.params && this.$route.params.id;
      if (bankId) {
        this.loading = true;
        turnExamplesByBankId({bankId}).then(response => {
           if (response.code === 200) {
             this.loading = false;
             this.$message({
               message: "转正式成功",
               type: "success"
             });
           }
        });
      }
    },
    toFormer(index, row) {
      console.log("选中：" + index);
      console.log("rows:" + JSON.stringify(row));
      turnExampleByWordId({"wordId": this.curWordId, "example": row.english + "-" + row.translation});
      this.openExamples = false;
      alert("已转正式");
      this.getList();


    },
    parseLanguagePairs(inputString) {
      // 使用正则表达式匹配每一对英文和翻译
      // 正则表达式解释：
      // ([^=&]+): 匹配等号(=)或和号(&)之前的所有字符，非贪婪匹配
      // (?:\=\s*): 匹配等号(=)，后面可能跟着一些空白字符
      // ([^&]+): 匹配和号(&)之前的所有字符，非贪婪匹配
      // 整个表达式放在括号内，表示捕获组，用于提取每一对匹配的文本
      const regex = /([^=&]+)(?:\=\s*)([^&]+)/g;
      let matches;
      const result = [];

      // 使用正则表达式进行全局匹配
      while ((matches = regex.exec(inputString)) !== null) {
        // matches[1] 是英文部分，matches[2] 是翻译部分
        // matches[1].trim(), matches[2].trim()
        result.push({
          english: matches[1].trim(),
          translation: matches[2].trim()
        });
      }

      return result;
    },

    playAudio(url) {
      this.audio.src = url; // 设置音频的src属性为点击的音频URL
      this.audio.play(); // 播放音频
    },
    /** 查询词汇原型列表 */
    getList(bankId) {
      this.loading = true;
      listItem(this.queryParams).then(response => {
        this.itemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        word: null,
        synonyms: null,
        usPhonetics: null,
        ukPhonetics: null,
        usVoice: null,
        ukVoice: null,
        wordType: null,
        updateTime: null,
        createTime: null,
        uid: null,
        meanings: null,
        meaning: null,
        chineseMeaning: null,
        picture: null,
        chosenExample: null,
        examples: null,
        bankId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加词汇";
    },

    /** 修改按钮操作 */
    handleExamples(row) {
      this.myExamples = this.parseLanguagePairs(row.examples);
      console.log(this.myExamples);
      if (this.myExamples.length === 0) {
        alert("没有例句!")
      }
      this.reset();
      this.titleExamples = "单选正式例句";
      this.curWordId = row.id;
      this.openExamples = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getItem(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改词汇";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除词汇编号为"' + ids + '"的数据项？').then(function () {
        return delItem(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('vocabulary-item/export', {
        ...this.queryParams
      }, `item_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
